"""
a queue processing daemon.

this could be a pub-sub thing, of course, listening for some....

nah.
"""
from ticket import Queue
from time import sleep

def process_queue(limit, verbosity, order_by, sleep_time, *args, **kwargs):
    """
    pull items off the ticket one at a time.
    """
    if limit > 0:
        itr = xrange(limit)
    else:
        def infiniterator():
            while True: yield 
        itr = infiniterator()
    
    for i in itr:
        """
        this could really be more efficient.
        """
        t = Queue.all().order_by(order_by).process_next()            
        if t is None: #queue is empty
            sleep(sleep_time)
            continue
        if verbosity > 0 and t.status in set(['TRANSIENT_FAILURE', 'PERMANENT_FAILURE', 'UNCAUGHT_EXCEPTION']):
            print "%s failed with status %s, error %s" % (unicode(t), t.status, t.error_msg)
        elif (verbosity>1):
            print "%s succeeded" % unicode(t)
    